angular.module('starter.controllers')
.controller('LoginCtrl', function($scope, museumFac, $stateParams, $interval, $location, $cookies) {
  $scope.change_language = function(id){
      $scope.language = id;
      var expireDate = new Date();  
    expireDate.setDate(expireDate.getDate() + 30);                
    $cookies.put('language', id, {'expires': expireDate.toUTCString()});
    location.reload();
    if(id == 0){
      document.getElementById('title').innerHTML = '提示';
      document.getElementById('windowclosebutton').value = '确定';
    }else{
      document.getElementById('title').innerHTML = 'Hint';
      document.getElementById('windowclosebutton').value = 'Confirm';
    }

  }

  $scope.getLanguage = function(){
      $scope.language = $cookies.get('language');
      if($scope.language){
          $scope.language = $scope.language;
      }else{
          $scope.language = 0;
      }
      if($scope.language == 0){
      document.getElementById('title').innerHTML = '提示';
      document.getElementById('windowclosebutton').value = '确定';
    }else{
      document.getElementById('title').innerHTML = 'Hint';
      document.getElementById('windowclosebutton').value = 'Confirm';
    }
  }
  $scope.getLanguage();

  $scope.user = {};

  // 验证号码为11位
  $scope.check_phone = function(){
    $scope.width1 = $scope.user.phone.length;
    if($scope.width1 == 11){
      $scope.getcode = 1;
    }else{
      $scope.getcode = 0;
    }
  }

  $scope.postCode = function(){
    museumFac.user.sendtoken({
      phone:$scope.user.phone
    },function(data){
        $scope.post_code = 1;

        $scope.time = 60;
        var stop = $interval(function() {
          $scope.time --;
          if($scope.time<=0){
              $interval.cancel(stop);
              stop = undefined;
              $scope.post_code = 0;
          }
        }, 1000);

      },function(data){
        alert(data.data.info);
    });
  }

  $scope.login = function(){
    museumFac.user.register({
      phone:$scope.user.phone,
      token:$scope.user.token
    },function(data){
        var lastpage = $cookies.get('lastPage');
        console.log(lastpage);
        if(lastpage){
          window.location.href = lastpage;
        }else{
          $location.url('home');
        }
      },function(data){
        // $scope.url = window.location.href;
        // $cookies.put('lastPage', $scope.url);
        alert(data.data.info);
    });
  }
  
})